import { defineStore } from "pinia";
import { TOKEN_KEY } from "@/enums/cacheEnum";
import Storage from "@/utils/storageCache";
// import { logout, refreshToken } from '@/services/auth';
import request from "@/utils/httpInterceptor";
import { TOKEN } from "@/utils/auth";
import { forIn } from "lodash";
interface AuthState {
  notice: AnyObject;
  pollingIntervalObjectFun:{
	  [key:string]:(()=>void)
  },
  userInfo:AnyObject;
}

export const LOGIN = "/u/app/account/login";
const WX_LOGIN = "/u/app/wx/login";
const LOGIN_OUT = "/logout";
const REFRESH_TOKEN = "/refresh/token";

export const useAuthStore = defineStore({
  id: "auth",
  state: (): AuthState => ({
    notice: {},
	pollingIntervalObjectFun:{},
	userInfo:{},

  }),
  getters: {

    // isLogin() {
    //   return Storage.get("userInfo")?.token;
    // },
    // userInfo: (): AnyObject => {
    //   return Storage.get("userInfo");
    // },
  },
  actions: {
	  
	  
	  /**
	   * @description 设置与取消轮询
	   */
	 async   setOrcancelPollingInterval(key?:string,value?:any){
		   if(!key){
			  for(let s in this.pollingIntervalObjectFun ){
				  this.pollingIntervalObjectFun[s]()
				  
			  }
			  this.pollingIntervalObjectFun={}
		   }else{
			   this.pollingIntervalObjectFun[key]=value
		   }
	  },

  
    /**
     * @description 登录
     */
    async login(params: LoginParams): Promise<LoginModel> {
      const res: any = await request({
        url: LOGIN,
        method: "POST",
        data: params,
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      });
      if (res?.code == "0") {
        Storage.set("userInfo", res?.data);
		this.userInfo=res?.data;
    
        return Promise.resolve(res?.data);
      }
      return Promise.reject(res);
    },
	
	
	async wxlogin(params: LoginParams): Promise<LoginModel> {
	  const res: any = await request({
	    url: WX_LOGIN,
	    method: "POST",
	    data: params,
	    header: {
	      "Content-Type": "application/x-www-form-urlencoded",
	    },
	  });
	  if (res?.code == "0") {
	    Storage.set("userInfo", res?.data);
		this.userInfo=res?.data;
	
	    return Promise.resolve(res?.data);
	  }
	  return Promise.reject(res);
	},
	
    /**
     * @description 登出
     */
    async loginOut(): Promise<any> {
      Storage.remove(TOKEN_KEY);
      return true;
    },
    /**
     * @description 刷新token
     */
    async refreshToken(): Promise<LoginModel> {
      try {
        // const { data } = await refreshToken();

        // return Promise.resolve(data);
      } catch (err) {
        // return Promise.reject(err);
      }
    },

    /**
     * @description 设置通知数
     */
    setNotice(params:AnyObject) {
      this.notice = params;
    },
  },
});
